<template>
  <!-- 预约表单填写 -->
  <div class="c-bg-sgray">
    <section
      @click="showSelectConsumption = true"
      class=" c-bg-white c-ph24 c-fs26 c-hh100 c-flex-row c-justify-sb c-aligni-center"
    >
      <div class="">咨询方式</div>
      <div class="c-fc-xblack">
        <span>{{ CONSUMPTION_MAP[consumptionPattern[0]] || "请选择咨询方式"}}</span>
        <i class="iconfont icon-jiantou c-fs22 c-fc-xblack"></i>
      </div>
    </section>
    <section class="c-mt16 c-bg-white c-ph24 c-fs26">
      <div class="c-hh100 c-flex-row c-justify-sb c-aligni-center c-bd-b1">
        <div class="">姓名 (必填)</div>
        <input
          type="text"
          v-model="name"
          placeholder="请输入您的姓名"
          class="c-textAlign-r c-bd0 c-fs26 c-fc-xblack"
        />
      </div>
      <div class="c-hh100 c-flex-row c-justify-sb c-aligni-center c-bd-b1 c-p">
        <div class="">电话 (必填)</div>
        <input
          type="tel"
          v-model="mobile"
          placeholder="请输入您的电话"
          maxlength="11"
          class="c-textAlign-r c-bd0 c-fs26 c-fc-xblack"
        />
        <!-- <div class="c-fs18 c-fc-sgray c-mt8 c-pa c-p-l0 c-p-b6">请保持⼿机畅通，方便特殊情况时我们和您联系。</div> -->
      </div>
      <div
        class="c-hh100 c-flex-row c-justify-sb c-aligni-center c-bd-b1"
        v-if="consumptionPattern[0] == 2"
      >
        <div class="">微信号 (必填)</div>
        <input
          type="text"
          v-model="wechat"
          placeholder="请输入您的微信号"
          class="c-textAlign-r c-bd0 c-fs26 c-fc-xblack"
        />
      </div>
      <div
        class="c-hh100 c-flex-row c-justify-sb c-aligni-center c-bd-b1"
        v-for="(item, index) in formList"
        :key="index"
      >
        <div class="">
          {{ item.fieldNo }} ({{ item.isReq == 1 ? "必填" : "选填" }})
        </div>
        <input
          type="text"
          v-model="item.value"
          :placeholder="'请输入' + item.fieldNo"
          class="c-textAlign-r c-bd0 c-fs26 c-fc-xblack"
        />
      </div>
      <div
        v-if="consumptionPattern[0] == 1 && address"
        class="c-hh100 c-flex-row c-justify-sb c-aligni-start c-bd-b1 c-pt12"
      >
        <div class="c-pr12">地址</div>
        <div class="c-fc-xblack c-textAlign-r c-w0 c-flex-grow1">{{ address }}</div>
      </div>
      <div class="c-hh100 c-flex-row c-justify-sb c-aligni-center" @click="clickShowTimePicker">
        <div class="">预约时间</div>
        <div class="c-fc-xblack" v-if="date || startAt || endAt">
          {{ date }} <span>{{ startAt }}{{startAt ? '-' : ''}}{{ endAt }}</span>
        </div>
        <div class="c-fc-sgray" v-else>
          请重新选择时间
        </div>
      </div>
    </section>
    <div
      class="c-mt16 c-bg-white c-pv30 c-ph24 c-fs26 c-flex-row"
      v-if="formData.instructions"
    >
      <div class="">预约说明</div>
      <div class="c-flex-grow1 c-w0 c-pl24 c-fc-xblack">{{ formData.instructions }}</div>
    </div>

    <div
      class="c-mt32 c-mh24 c-hh72 c-br36 theme-bg c-fc-white c-fs28 c-flex-row c-flex-center"
      @click="clickSubmit"
    >
      立即提交
    </div>
    <div class="c-fs20 c-fc-sblack c-mt32 c-textAlign-c">请保持⼿机畅通，方便特殊情况时我们和您联系。</div>
    <div v-transfer-dom>
      <popup-picker
        v-if="showSelectConsumption"
        :show.sync="showSelectConsumption"
        :data="consumptionList"
        :show-name="true"
        v-model="consumptionPattern"
      ></popup-picker>
    </div>
    <!-- 半弹窗预约时间 -->
    <open-modal :openModal="showTimePicker" @closeModal="hiddenTimePicker">
      <div class="c-bg-white c-br-tl32 c-br-tr32 c-text-hidden c-maxw640 c-pb20 c-p c-pz1000">
        <div class="c-fs28 c-fw-b c-textAlign-c c-pv36">可约时间</div>
        <div @click="hiddenTimePicker" class="c-fs28 c-fc-gray iconfont c-p-t40 c-p-r24 c-pa">&#xe84e;</div>
        <div class="c-ph24 c-pb120">
          <div class="c-bd1 c-br16 c-pv22">
            <div class="c-maxh720" :class="isShowMonth ? '' : 'c-contexty-scroll'">
              <time-picker
                ref="timePicker"
                @chooseTime="chooseTime"
                @clickChooseDate="clickChooseDate"
                @clickEdit="clickEdit"
                @closeopenCalendarModal="closeopenCalendarModal"
                @clickMoreDay="clickMoreDay"
                @confirmCalendarDay="confirmCalendarDay"
              ></time-picker>
            </div>
            <div class="c-w100 c-ph24 c-pv18 c-bg-white c-pf c-p-b0 c-p-l0 c-p-r0 c-m-0auto">
              <div class="c-w100 c-hh64 c-lh64 c-fs26 c-textAlign-c c-br32 theme-bg c-fc-white" @click="clickNewDate" >确认修改</div>
            </div>
          </div>
        </div>
      </div>
    </open-modal>
    <!-- 自选时间--按分钟预约时间间隔 -->
    <open-modal :openModal="showTime" @closeModal="closeChooseTime">
      <div class="c-bg-white c-br-tl32 c-br-tr32 c-text-hidden c-maxw640 c-pb20 c-p c-pz1000">
        <div class="c-fs28 c-fw-b c-textAlign-c c-pv36">可约时间</div>
        <div @click="closeChooseTime" class="c-fs28 c-fc-gray iconfont c-p-t40 c-p-t24 c-p-r24 c-pa">&#xe84e;</div>
        <div class="c-ph24 c-pb120">
          <div class="c-bd1 c-br16 c-pv22">
            <div class="c-contexty-scroll c-maxh720">
              <time-picker
                ref="dayTimePicker"
                @chooseTime="chooseTime"
              >
                <template v-slot>
                  <div class="c-w100 c-ph24 c-pv18 c-bg-white c-pf c-p-b0 c-p-l0 c-p-r0 c-m-0auto">
                    <div class="c-w100 c-hh64 c-lh64 c-fs26 c-textAlign-c c-br32 theme-bg c-fc-white" @click="clickNewDate(1)" >确认修改</div>
                  </div>
                </template>
              </time-picker>
            </div>
          </div>
        </div>
      </div>
    </open-modal>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js";
import { PopupPicker, TransferDom } from "ckjrweb-mp-ui/src/components/index";
import TimePicker from "@/components/templates/timePicker.vue";
import OpenModal from "@/components/templates/common/openModal.vue";
let inputScrollTop = 0;
let isLoading = false;
const CONSUMPTION_MAP = {
  1: "面对面咨询",
  2: "微信咨询",
  3: "电话咨询",
  4: "线上连麦咨询",
};
export default {
  name: "bookingForm",
  directives: {
    TransferDom
  },
  components: {
    PopupPicker,
    TimePicker,
    OpenModal
  },
  props: [],
  beforeCreate() {},
  data() {
    return {
      CONSUMPTION_MAP: CONSUMPTION_MAP,
      showSelectConsumption: false,
      consumptionList: [],
      consumptionPattern: [],
      name: "",
      mobile: "",
      wechat: "",
      formData: "",
      formList: [],
      atId: "",
      atmId: "",
      date: "",
      startAt: "",
      endAt: "",
      showTimePicker: false, // 是否展示时间选择
      isLoading: false,
      dateInfo: null, // 时间选择
      hasGetCalendar: false, // 已经获取预约时间
      bookingList: null,
      timeType: 0,
      dateType: 1,
      enableEnroll: true,
      showTime: false,
      isShowMonth: false,
    };
  },
  created() {
    utilJs.appShare(this);
  },
  methods: {
    // 月份选择器选择date
    confirmCalendarDay(date) {
      this.date = date;
      this.isShowMonth = false;
    },
    // 关闭月份选择弹窗
    closeopenCalendarModal() {
      this.isShowMonth = false;
    },
    // 选择月份
    clickMoreDay() {
      this.isShowMonth = true;
    },
    closeChooseTime() {
      this.showTime = false;
      if (this.showTimePicker) this.showTimePicker = false;
      this.isShowMonth = false;
      this.dateInfo = null;
    },
    // 选择 日期分钟
    chooseTime(data) {
      this.dateInfo = data;
    },
    // 选择 日期时间段
    clickChooseDate(data) {
      this.dateInfo = data;
    },
    checkEnrollTime(atmId) {
      return new Promise((resolve, reject) => {
        utilJs.getMethod(`${global.apiurl}appointment/checkEnrollTime?atmId=${atmId}`, res => {
          // 1：可预约；2：预约人数已满；3：预约时间已过期；4：已过截止预约时间
          resolve(res)
        }, () => {
          reject(false);
        })
      });
    },
    // 确认修改
    async clickNewDate(type) {
      if (!this.dateInfo) {
        this.$showCjToast({
          text: "请选择预约时间",
          type: "warn",
        });
        return;
      }
      let data = this.dateInfo;
      if (data.date && data.atmId) {
        // 主要处理的是按天预约不用细分到分钟的流程
        const status = await this.checkEnrollTime(data.atmId);
        // 1：可预约；2：预约人数已满；3：预约时间已过期；4：已过截止预约时间
        if (this.enrollEndTime && this.enrollEndTime != 0 && this.enrollEndUnit && status >= 2) {
          let time = status == 4 ? `${this.enrollEndTime}${this.enrollEndUnit == 1 ? '分钟' : this.enrollEndUnit == 2 ? '小时' : '天'}` : '';
          let msg = status == 2 ? `预约人数已满` :
                    status == 3 ? `预约时间已过期` :
                    status == 4 ? `该服务开始前${time}停止预约。请合理规划时间，提前完成预约，避免错过。如有疑问，可联系商家，感谢您的理解和配合！` : ''
          this.$cjConfirm({
            title: '提示',
            message: msg,
            showCancelButton: false,
            clickCloseModal: false,
            onConfirm:() => {
              this.closeChooseTime();
              this.hiddenTimePicker();
              // 自选日期后面再选择选择时间段如果预约不到时间，则都清空
              if (this.dateType == 1 && this.timeType == -1) {
                this.date = '';
                this.atmId = '';
                this.startAt = '';
                this.endAt = '';
              }
            }
          })
          return;
        }
      }
      this.date = data.date;
      this.atmId = data.atmId;
      this.startAt = data.startAt;
      this.endAt = data.endAt;
      if (this.date && !this.startAt && !this.endAt) {
        this.showDayTimePicker();
        return
      }
      if (type == 1) {
        this.closeChooseTime();
      } else {
        this.hiddenTimePicker();
      }
    },
    // 点击显示按日期选择分钟间隔时间段
    showDayTimePicker() {
      if (this.showTime) {
        if (this.date == "" || this.startAt == "" && !(this.dateType == 1 && this.timeType == -1)) {
          this.$showCjToast({
            text: "请选择预约时间",
            type: "warn",
          });
          return;
        }
      }
      this.showTime = true;
      this.$nextTick(() => {
        this.$refs.dayTimePicker.publicInitData({
          bookingList: this.bookingList,
          dateType: this.dateType,
          timeType: this.timeType,
          date: this.date,
          atmId: this.atmId,
          enableEnroll: this.enableEnroll,
          curSelectDate: this.curSelectDate,
          teacherStatus: this.formData.teacherStatus,
          isFromScheduling: this.isFromScheduling,
          showTime: true,
          atId: this.atId
        })
      })
    },
    // 获取预约时间
    getCalendar() {
      if (this.isLoading) {
        return;
      }
      this.isLoading = true;
      utilJs.getMethod(`${global.apiurl}appointment/getDateList?atId=${this.atId}&type=1`, res => {
        this.isLoading = false;
        this.bookingList = res.details; //可预约时间
        this.hasGetCalendar = true;
        let dateList = [];
        for (let key of this.bookingList) {
          let type = 0;
          let nowDayStr = utilJs.dateFormat(+new Date()); //获取今天的日期
          if (key.date >= nowDayStr && key.isFull != 1 && key.isEnroll != 1) {
            type = 1;
          }
          if (res.allDay == 1 && key.date == nowDayStr) {
            let cDStartTimeTamp = new Date(key.date.replace(/-/g, "/") + ' ' + key.startAt).getTime();
            let nowTimeTamp = new Date().getTime();
            if (cDStartTimeTamp < nowTimeTamp) {
              type = 0;
            }
          }
          let item = {
            atId: key.atId,
            atmId: key.atmId,
            date: key.date,
            isFull: key.isFull,
            type: type,
            week: key.week,
            number: key.number,
            isEnroll: key.isEnroll,
          }
          if (res.allDay == 1) {
            item.startAt = key.startAt;
            item.endAt = key.endAt;
            item.status = key.status;
          }
          dateList.push(item);
        };
        this.bookingList = dateList;
        this.dateType = res.dateType;
        this.timeType = res.allDay;
        this.enableEnroll = res.enableEnroll;
        this.$nextTick(() => {
          let data = {
            bookingList: this.bookingList,
            dateType: res.dateType,
            timeType: res.allDay,
            enableEnroll: res.enableEnroll,
            atId: this.atId,
            curSelectDate: this.date,
            isFromForm: true,
            teacherStatus: this.formData.teacherStatus,
          }
          // 自选日期后面再选择选择时间
          if (!(this.dateType == 1 && this.timeType == -1)) {
            data.date = this.date;
            data.atmId = this.atmId;
          }
          this.$refs.timePicker.publicInitData(data)
        })
        if (this.dateType == 1 && this.timeType == -1) {
          this.startAt = '';
          this.endAt = '';
        }
      }, failRes => {
        this.isLoading = false;
      });
    },
    hiddenTimePicker() {
      this.showTimePicker = false;
      if (this.showTime) this.showTime = false;
    },
    clickShowTimePicker() {
      if (this.date && !this.startAt && !this.endAt) {
        this.showDayTimePicker();
        return
      }
      this.showTimePicker = true;
      if (this.hasGetCalendar == false) {
        this.getCalendar();
      } else {
        this.$nextTick(() => {
          this.$refs.timePicker.publicInitData({
            bookingList: this.bookingList,
            dateType: this.dateType,
            timeType: this.timeType,
            date: this.date,
            atmId: this.atmId,
            enableEnroll: this.enableEnroll,
            atId: this.atId,
            curSelectDate: this.date,
            isFromForm: true,
          })
        })
      }
    },
    //获取预约信息
    getFormData() {
      if (!this.isLoading) {
        this.isLoading = true;
        utilJs.getMethod(
          `${global.apiurl}appointment/getEnrollBaseInfo?atId=${this.atId}`,
          (res) => {
            this.isLoading = false;
            this.formData = res;
            this.formList = res.fields;
            this.address = res.place + (res.address && res.address[0] ? res.address[0].address : '');
            this.enrollEndTime = res.enrollEndTime;
            this.enrollEndUnit = res.enrollEndUnit;
            let consumptionArr = [];
            for (let item of res.consumptionPatterns) {
              let info = {
                name: CONSUMPTION_MAP[item],
                value: item,
              };
              //如果是连麦咨询的话，必须开启直播才能可以选择
              if (item != 4 || (item == 4 && res.enableChoiceLive == 1)) {
                consumptionArr.push(info);
              }
            }
            this.consumptionList = [consumptionArr];
            console.log('-this.consumptionList-', this.consumptionList, this.consumptionPattern)
          },
          (failRes) => {
            this.isLoading = false;
          }
        );
      }
    },
    //此处产品要求手机号只要小于11位数字即可
    isPhoneNumber: (phoneStr) => {
      var mobile = /^(\d{1,11})$/;
      return mobile.test(phoneStr);
    },
    checkForm() {
      if (this.consumptionPattern && this.consumptionPattern.length == 0) {
        this.$showCjToast({
          text: "请选择咨询方式",
          type: "warn",
        });
        return false;
      }
      if (!this.name || !this.mobile) {
        this.$showCjToast({
          text: "必填信息不能为空",
          type: "warn",
        });
        return false;
      }
      if (this.consumptionPattern[0] == 2 && !this.wechat) {
        this.$showCjToast({
          text: "必填信息不能为空",
          type: "warn",
        });
        return false;
      }
      if (!this.isPhoneNumber(this.mobile)) {
        this.$showCjToast({
          text: "请输入正确的手机号",
          type: "warn",
        });
        return false;
      }
      let hasNoInputReq = this.formList.some((i) => i.isReq == 1 && !i.value);
      if (hasNoInputReq) {
        this.$showCjToast({
          text: "请完成表单",
          type: "warn",
        });
        return false;
      }
      if (this.atmId == "") {
        this.$showCjToast({
            text: "请选择预约时间",
            type: "warn",
            time: 3000
          });
          return false;
        }
      return true;
    },
    clickSubmit() {
      if (!this.checkForm()) {
        return;
      }
      let valueArr = [];
      for (var i in this.formList) {
        valueArr.push({
          isReq: this.formList[i].isReq,
          name: this.formList[i].fieldNo,
          value: this.formList[i].value,
        });
      }

      let bookingInfo = {
        orderId: "",
        atmId: this.atmId,
        atId: this.atId,
        consumptionPattern: this.consumptionPattern[0],
        name: this.name,
        mobile: this.mobile,
        fieldVal: JSON.stringify(valueArr),
        address: this.address,
        wxNumber: this.wechat,
      };
      if (this.formData.deposit != null && this.formData.deposit != undefined && Number(this.formData.deposit) == 0) {
        this.submitForm(bookingInfo);
      } else {
        let goPath = `/homePage/course/coursePay?cId=-1&extId=${
          this.atmId
        }&ckFrom=${
          global.ckFrom.booking
        }&isFromInvite=0&bookingInfo=${JSON.stringify(bookingInfo)}`;
        goPath = this.goodsRoomId
          ? `${goPath}&goodsRoomId=${this.goodsRoomId}`
          : goPath;
        this.$routerGo(this, "push", { path: goPath });
      }
    },
    //提交表单
    submitForm(bookingInfo) {
      if (isLoading) {
        return;
      }
      let $this = this;
      isLoading = true;
      utilJs.postMethod(
        `${global.apiurl}appointment/createEnroll`,
        bookingInfo,
        function(res) {
          isLoading = false;
          $this.$cjConfirm({
            message:  "提交成功！",
            showCancelButton: false,
            onConfirm:() => {
              $this.$routerGo($this, "push", {
                path: "/member/myBooking/myBookingList",
                query: { isFromOrder: 1 }
              });
            }
          })
        },
        (failRes) => {
          isLoading = false;
        }
      );
    },
    //IOS微信6.7以上版本会导致输入法收起的时候，键盘没收起，需要手动滚下屏幕
    inputFocus() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        inputScrollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    inputBlur() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = inputScrollTop - 1 || 0;
        });
      }
    },
    //分享
    wechatShare: function() {
      let title = this.formData.name || "";
      let shareImg = this.formData.headimg;
      let shareUrl = `${
        window.location.href.split("#")[0]
      }#/homePage/booking/bookingTime?atId=${
        this.atId
      }&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.formData.desc;
      utilJs.wechatConfig(
        shareUrl,
        title,
        shareImg,
        shareDesc,
        function() {},
        true
      );
    },
    //手机端分享
    appShare: function() {
      let title = this.formData.name || "";
      let shareImg = this.formData.headimg;
      let shareUrl = `${
        window.location.href.split("#")[0]
      }#/homePage/booking/bookingTime?atId=${
        this.atId
      }&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.formData.desc;
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
  },
  activated() {
    this.formData = "";
    this.formList = [];
    this.atId = this.$route.query.atId || "";
    this.atmId = this.$route.query.atmId || "";
    this.date = this.$route.query.date || "";
    this.startAt = this.$route.query.startAt || "";
    this.endAt = this.$route.query.endAt || "";
    this.timeType = this.$route.query.timeType || "";
    this.goodsRoomId = this.$route.query.goodsRoomId || "";
    this.consumptionList = [];
    this.consumptionPattern = [];
    this.showSelectConsumption = false;
    this.address = "";
    this.hasGetCalendar = false;
    this.showTimePicker = false; // 是否展示时间选择
    this.isShowMonth = false;
    this.isLoading = false;
    this.dateInfo = {
      date: this.date,
      atmId: this.atmId,
      startAt: this.startAt,
      endAt: this.endAt,
    }; // 时间选择
    this.hasGetCalendar = false; // 已经获取预约时间
    this.timeType = 0;
    this.dateType = 1;
    this.enableEnroll = true;
    this.getFormData();
    this.wechatShare();
  },
};
</script>

<style scoped>
::-webkit-input-placeholder {
  /* WebKit browsers */
  color: #ccc;
}
:-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: #ccc;
}
::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #ccc;
}
:-ms-input-placeholder {
  /* Internet Explorer 10+ */
  color: #ccc;
}
</style>
